import os
import filecmp
import shutil
import subprocess
import tempfile
import stat
import pwd
import grp
import os.path
import time

class ConfigureFiles:
    def __init__(self, files):
        self.files = files
        self.successful = 0
        self.failed     = 0
        self.oo_sync    = 0

    def configure(self):
        """
        Configure file resources.
        """
        print "\033[1;36m- Configuring Files\033[1;m"
        runtime_start = time.time()
        for file in self.files:
            old_file_path = self.files[file]['path']
            new_file_mode = self.files[file]['mode']
            new_file_uid  = self.files[file]['owner']
            new_file_gid  = self.files[file]['group']
            old_file      = "%s%s" % (old_file_path, file)

            # Setup and write incoming file content to tempfile.
            t = tempfile.NamedTemporaryFile()
            t.write(self.files[file]['content'])
            t.flush()

            new_file = t.name
            # Check if the file resource exist on the client
            if os.path.isfile(old_file):
                stat_info = os.stat(old_file)
                old_file_mode  = stat.S_IMODE(stat_info.st_mode)
                old_file_owner = pwd.getpwuid(stat_info.st_uid)[0]
                old_file_group = grp.getgrgid(stat_info.st_gid)[0]
                # Compare exsiting file and incoming changes
                if filecmp.cmp(old_file, new_file):
                    self.successful += 1
                    pass
                else:
                    # Show diff and overwrite exsiting file with temp
                    self.diff_files(old_file, new_file)
                    shutil.copy(new_file, old_file)

                    # Does current file mode match resource requirements?
                    if old_file_mode == new_file_mode:
                        pass
                    else:
                        uid = pwd.getpwnam(new_file_uid)[2]
                        gid = grp.getgrnam(new_file_gid)[2]
                        os.chown(old_file,uid,gid)
                        subprocess.call(['chmod', new_file_mode, old_file])
                    self.oo_sync += 1
            else:
                print "% not found, skipping." % (old_file)
                self.failed += 1
            # Close temporary file.
            t.close()

        runtime_end = time.time()
        runtime = (runtime_end - runtime_start)

        stats = {
            'runtime'   : runtime,
            'successful': self.successful,
            'failed'    : self.failed,
            'oo_sync'   : self.oo_sync
        }

        return stats

    def diff_files(self, file1, file2):
        """
        Diff two files by shelling out to local system diff command.
        Make this configurable?
        """
        subprocess.call(['/usr/bin/diff', file1, file2])
